<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/22
 * Time: 17:36
 */

namespace base;


class BaiduPush
{
    /**
     * 百度推送地址
     * @var string
     */
    protected $pushUrl = 'http://data.zz.baidu.com/urls?';

    /**
     * 站点地址
     * @var string
     */
    protected $site = '';

    /**
     * TOKEN
     * @var string
     */
    protected $token = '';

    /**
     * 单例对象
     * @var
     */
    private static $_instance;

    /**
     * 初始化
     * @param string $site 站点地址 www.dadiba.net
     * @param string $token TOKEN
     * @return static
     */
    public static function init($site, $token)
    {
        if (empty(self::$_instance)) {
            self::$_instance = new static($site, $token);
        }
        return self::$_instance;
    }

    /**
     * 构造方法
     * BaiduPush constructor.
     * @param string $site 站点地址 www.dadiba.net
     * @param string $token TOKEN
     */
    public function __construct($site, $token)
    {
        $this->site  = $site;
        $this->token = $token;
    }

    /**
     * 推送连接
     * @param array $urls
     * @return mixed
     */
    public function push($urls)
    {
        if (!is_array($urls)) {
            $urls = [$urls];
        }
        $apiUrl = $this->_getApiUrl();
        $result = $this->_doCurl($apiUrl, $urls);
        return $result;
    }

    /**
     * 获取接口地址
     * @return string
     */
    private function _getApiUrl()
    {
        $arr = [
            'site'  => $this->site,
            'token' => $this->token,
        ];
        return $this->pushUrl . http_build_query($arr);
    }

    /**
     * 执行查询
     * @param string $url 接口地址
     * @param array $params 参数
     * @return mixed
     */
    private function _doCurl($url, $params)
    {
        $ch      = curl_init();
        $options = [
            CURLOPT_URL            => $url,
            CURLOPT_POST           => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS     => implode("\n", $params),
            CURLOPT_HTTPHEADER     => ['Content-Type: text/plain'],
        ];
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}